<template>
  <a-space>
    <a-input-group>
      <a-select v-model="searchValue.keywordType" :style="{ width: '100px' }">
        <a-option value="asin">ASIN</a-option>
        <a-option value="sku">MSKU</a-option>
      </a-select>
      <a-input :style="{ width: '160px' }" v-model="searchValue.keyword" allow-clear placeholder="请输入" />
    </a-input-group>

    <a-select v-model="searchValue.states" :style="{ width: '160px' }" allow-clear placeholder="请选择">
      <a-option value="ENABLED">投放中</a-option>
      <a-option value="PAUSED">已暂停</a-option>
      <a-option value="ARCHIVED">已归档</a-option>
    </a-select>
    <a-range-picker v-model="searchValue.time" :style="{ width: 300 + 'px' }" :allow-clear="false" shortcuts-position="left" :shortcuts="rangeShortcuts()" />
    <a-button class="gray-outline" @click="search">搜索</a-button>
  </a-space>
  <showStatics class="mt5" :list="list" />
  <a-space class="mt5">
    <a-button class="gray-outline" :disabled="props.info.adType === 'SPONSORED_BRANDS'" @click="changeStatus('ENABLED')">启用</a-button>
    <a-button class="gray-outline" :disabled="props.info.adType === 'SPONSORED_BRANDS'" @click="changeStatus('PAUSED')">暂停</a-button>
    <a-button class="gray-outline" :disabled="props.info.adType === 'SPONSORED_BRANDS'" @click="changeStatus('ARCHIVED')">归档</a-button>
  </a-space>
  <a-table class="mt5 table-two-line" row-key="id" :loading="tableLoading" size="mini" @sorter-change="sorterChange" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" v-model:selectedKeys="ids" :pagination="false" :data="tableDate" :scroll="{ y: '300px', x: '100%' }">
    <template #columns>
      <a-table-column :width="80" title="有效" fixed="left">
        <template #cell="{ record }">
          <a-popconfirm v-if="record.state != 'ARCHIVED'" :content="`确定是否${record.state === 'PAUSED' ? '开启' : '暂停'}商品`" @ok="changeState(record.state, record)" type="warning">
            <a-switch v-model="record.state" :disabled="props.info.adType === 'SPONSORED_BRANDS'" size="medium" checked-value="ENABLED" unchecked-value="PAUSED" :beforeChange="() => false">
              <template #checked> 开 </template>
              <template #unchecked> 关 </template>
            </a-switch>
          </a-popconfirm>
          <a-switch v-else v-model="record.state" disabled checked-value="ENABLED" unchecked-value="ARCHIVED" />
        </template>
      </a-table-column>
      <a-table-column :width="200" title="商品" fixed="left">
        <template #cell="{ record }">
          <div class="flex-c">
            <ImgPopover :src="record.asinImageUrl || record.asinSmallImageUrl" :isPre="true">
              <template #con>
                <a-image width="40" :preview="false" height="40" fit="contain" :src="record.asinSmallImageUrl || record.asinImageUrl" />
              </template>
            </ImgPopover>
            <div style="margin-left: 5px; width: 140px" class="highlight">
              <a-typography-paragraph copyable :copy-text="record.asinUrl" style="margin-bottom: 0" :copy-tooltip-props="{ mini: true }">
                <a-button style="line-height: 20px; height: 20px" type="text">{{ record.asin }}</a-button>
              </a-typography-paragraph>
              <TextLimit :rows="1">{{ record.sku }}</TextLimit>
            </div>
          </div>
        </template>
      </a-table-column>
      <a-table-column :width="70" title="状态" fixed="left">
        <template #cell="{ record }">
          <p :class="$extract(statusMap[record.state], 'color')">{{ $extract(statusMap[record.state], 'name') }}</p>
        </template>
      </a-table-column>

      <a-table-column :width="85" align="right" title="曝光量" :sortable="sortable" data-index="impressions">
        <template #cell="{ record }">
          <p v-if="record.impressions || record.impressions === 0">{{ record.impressions }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="85" title="点击量" align="right" :sortable="sortable" data-index="clicks">
        <template #cell="{ record }">
          <p v-if="record.clicks || record.clicks === 0">{{ record.clicks }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="75" title="CTR" align="right" :sortable="sortable" data-index="ctr">
        <template #cell="{ record }">
          <p v-if="record.ctr || record.ctr === 0">{{ Number(record.ctr).toFixed(2) }}%</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="80" title="花费" align="right" :sortable="sortable" data-index="cost">
        <template #cell="{ record }">
          <p v-if="record.cost || record.cost === 0">${{ Number(record.cost).toFixed(2) }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="80" title="CPC" align="right" :sortable="sortable" data-index="cpc">
        <template #cell="{ record }">
          <p v-if="record.cpc || record.cpc === 0">${{ Number(record.cpc).toFixed(2) }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="75" title="CVR" align="right" :sortable="sortable" data-index="cvr">
        <template #cell="{ record }">
          <p v-if="record.cvr || record.cvr === 0">{{ Number(record.cvr).toFixed(2) }}%</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="80" title="CPA" align="right" :sortable="sortable" data-index="cpa">
        <template #cell="{ record }">
          <p v-if="record.cpa || record.cpa === 0">${{ Number(record.cpa).toFixed(2) }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="85" title="总单量" align="right" :sortable="sortable" data-index="purchasesOrder">
        <template #cell="{ record }">
          <p v-if="record.purchasesOrder || record.purchasesOrder === 0">{{ record.purchasesOrder }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="95" title="商品销量" align="right" :sortable="sortable" data-index="purchasesSale">
        <template #cell="{ record }">
          <p v-if="record.purchasesSale || record.purchasesSale === 0">{{ record.purchasesSale }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="95" title="销售额" align="right" :sortable="sortable" data-index="saleAmount">
        <template #cell="{ record }">
          <p v-if="record.saleAmount || record.saleAmount === 0">${{ Number(record.saleAmount).toFixed(2) }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="85" title="ACOS" align="right" :sortable="sortable" data-index="acos">
        <template #cell="{ record }">
          <p v-if="record.acos || record.acos === 0">{{ Number(record.acos).toFixed(2) }}%</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="85" title="ROAS" align="right" :sortable="sortable" data-index="roas">
        <template #cell="{ record }">
          <p v-if="record.roas || record.roas === 0">{{ Number(record.roas).toFixed(2) }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
    </template>
  </a-table>
  <div class="pagination-footer mt10">
    <a-pagination size="mini" :total="pagination.total" :default-page-size="pagination.pageSize" :current="pagination.pageNum" :page-size-options="[20, 50, 100, 200, 300]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue'
  import { rangeShortcuts, getStartAndEndTime } from '../../../common'
  import { AdStatusHandle } from '../../../types'
  import { getAdProductList, adGroupMetrics, updateAdProduct } from '@/api/advert'
  import { Message, Modal } from '@arco-design/web-vue'
  import showStatics from './showStatics.vue'
  const props = defineProps(['info'])
  const sortable: any = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  })
  const statusMap = {
    ENABLED: { name: '投放中', color: 'success' },
    PAUSED: { name: '已暂停', color: 'normal' },
    ARCHIVED: { name: '已归档', color: 'gray' },
  }

  let pagination = ref({ total: 0, pageSize: 20, pageNum: 1 })

  let searchValue = ref<any>({
    keywordType: 'asin',
    keyword: '',
    states: 'ENABLED',
    time: getStartAndEndTime('last_30_days'),
    orderItems: null,
  })
  let tableLoading = ref(false)
  let submitLoading = ref(false)
  let tableDate = ref([])
  let ids = ref([])
  let list = ref([
    { key: 'impressions', name: '曝光量', currency: '', num: '', isCount: true },
    { key: 'clicks', name: '点击量', currency: '', num: '', isCount: true },
    { key: 'ctr', name: '点击转化率CTR', currency: '', num: '', isCount: false, isPercentage: true },
    { key: 'purchasesSale', name: '广告销量', currency: '', num: '', isCount: true },
    { key: 'cvr', name: '销量转化率CVR', currency: '', num: '', isCount: false, isPercentage: true },
    { key: 'cost', name: '花费', currency: '$', num: '', isCount: true },
    { key: 'cpc', name: 'CPC', currency: '$', num: '', isCount: false },
    { key: 'saleAmount', name: '广告销售额', currency: '$', num: '', isCount: true, isPercentage: true },
    { key: 'acos', name: 'ACOS', currency: '', num: '', isCount: false },
    { key: 'roas', name: 'ROAS', currency: '', num: '', isCount: false },
  ])

  const search = () => {
    getMetricsData()
    getTableList()
  }

  const sizeChange = (val: number) => {
    pagination.value.pageNum = 1
    pagination.value.pageSize = val
    getTableList()
  }
  const changePage = (val: number) => {
    pagination.value.pageNum = val
    getTableList()
  }

  // 排序
  const sorterChange = (dataIndex: string, direction: string) => {
    if (!direction) {
      searchValue.value.orderItems = null
    } else {
      searchValue.value.orderItems = [
        {
          asc: direction == 'ascend' ? true : false,
          column: dataIndex,
        },
      ]
    }
    getTableList()
  }

  const getTableList = async () => {
    let params = {
      ...searchValue.value,
      campaignId: props.info.campaignId,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      startDate: searchValue.value.time[0],
      endDate: searchValue.value.time[1],
      orderItems: searchValue.value.orderItems,
      states: searchValue.value.states.split(','),
    }

    params[searchValue.value.keywordType] = searchValue.value.keyword

    tableLoading.value = true
    const res: any = await getAdProductList(params)
    tableLoading.value = false
    if (res) {
      pagination.value.total = res?.data?.total
      tableDate.value = res.data.data || []
      tableDate.value.forEach((el: any) => {
        el.id = el.shopId + el.campaignId + el.adId
      })
    }
  }

  const getMetricsData = async () => {
    let params = {
      states: searchValue.value.states.split(','),
      campaignId: props.info.campaignId,
      startDate: searchValue.value.time[0],
      endDate: searchValue.value.time[1],
    }
    params[searchValue.value.keywordType] = searchValue.value.keyword
    const res: any = await adGroupMetrics(params)
    list.value.forEach((e: any) => {
      e.num = res.data[e.key]
    })
  }

  // 单个修改广告组状态
  function changeState(state: any, item: any) {
    let status = state === 'PAUSED' ? 'ENABLED' : 'PAUSED'
    requestUpdataState([item], status)
  }
  //修改广告组状态请求
  async function requestUpdataState(list: Array<any>, state: string, msg?: string) {
    let params = list.map((el: any) => {
      return {
        adGroupId: el.adGroupId,
        campaignId: el.campaignId,
        adType: el.adType,
        shopId: el.shopId,
        state: state,
        asin: el.asin,
        adId: el.adId,
        adName: el.adName,
      }
    })
    submitLoading.value = true
    const res: any = await updateAdProduct(params)
    submitLoading.value = false
    if (!res) return
    getTableList()
    if (msg) {
      Message.success(msg)
    }
  }

  // 批量修改广告组状态
  function changeStatus(status: any) {
    if (!ids.value.length) {
      return Message.error('请选择商品')
    }
    Modal.confirm({
      title: '调整状态',
      content: `请再次确认，将选中的商品设置为${AdStatusHandle[status]}`,
      cancelText: '取消',
      okText: '确认',
      onOk: async () => {
        let arr = <Array<any>>[]
        ids.value.forEach((el: any) => {
          let item = tableDate.value.find((e: any) => e.shopId + e.campaignId + e.adId == el)
          if (item) arr.push(item)
        })
        requestUpdataState(arr, status, '设置成功')
        ids.value = []
      },
    })
  }

  onMounted(() => {
    getTableList()
    getMetricsData()
  })
</script>

<style lang="less" scoped></style>
